import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_question.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/post/post_detail_page.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/pd_banner.dart';
import 'package:osc/ui/widgets/real_rich_text.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///问答
class QuestionList extends StatefulWidget {
  final int catalog;
  final bool isNews;
  final bool isRecommendBlog;
  final bool needLogin;
  final bool enableLoadMore;
  final bool showBanner;
  final int authorId;
  final String authorName;

  /// catalog为资讯可选参数，authorUid、authorName为博客参数
  const QuestionList({Key key, this.catalog, this.needLogin = false, this.enableLoadMore = true, this.isNews = false, this.authorId = 0, this.authorName, this.showBanner = false, this.isRecommendBlog = false}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new QuestionListState(catalog, needLogin, enableLoadMore, isNews, authorId, authorName, showBanner, isRecommendBlog);
  }
}

class QuestionListState extends State<QuestionList> with AutomaticKeepAliveClientMixin<QuestionList> {
  final int catalog;
  final bool isNews;
  final bool isRecommendBlog;
  final bool needLogin;
  final bool enableLoadMore;
  final bool showBanner;
  final int authorId;
  final String authorName;
  QuestionListState(this.catalog, this.needLogin, this.enableLoadMore, this.isNews, this.authorId, this.authorName, this.showBanner, this.isRecommendBlog);

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscQuestion> list;

  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollPhysics scrollPhysics = ScrollPhysics();

  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: enableLoadMore,
      child: showBanner? buildListViewWithBanner() : buildListView(),
    );
  }

  buildListViewWithBanner(){
    return ListView(
      physics: scrollPhysics,
      children: <Widget>[
        PdBanner(catalog: isNews? 1 : 4, delay: 5000,),
        buildListView(),
      ],
    );
  }


  buildListView(){
    return ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        if(needLogin && !OscUserManager().isLogin()){
          return NoDataWidget(text: StringIds.userNoLogin,);
        } else {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
      shrinkWrap: showBanner,
      physics: scrollPhysics,
    );
  }

  buildListItem(int index){
    OscQuestion item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
        jump2PageForResult(PostDetailPage(id: item.id, type: 2,));
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
                padding: EdgeInsets.only(right: Dimens.gap_view_normal),
              child: OscPortraitWidget(portraitImageUrl: item.authorPortrait),
            ),
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(item.title, style: MyTextStyle.USER_LIST_TITLE,),
                    buildDescription(item.body),
                    buildBottom(item),
                  ],
                ),
            ),
          ],
        ),
      ),
    );
  }

  buildTitle(String title){
    return buildText(title, Colors.black, Dimens.font_sp14);
  }

  buildTextSpan(String text){
    return TextSpan(
      text: text,
      style: TextStyle(color: Colors.black, fontSize: Dimens.font_sp14,),
    );
  }

  buildImageSpan(String imageName, EdgeInsets margin){
    return ImageSpan(
      AssetImage(PdUtil.getImagePath(imageName)),
      imageWidth: Dimens.view_item_tag_height_small,
      imageHeight: Dimens.view_item_tag_height_small,
      margin: margin,
    );
  }
  
  buildTitleIcon(bool show, String imageName){
    return Offstage(
      offstage: !show,
      child: Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_tag_height_smaller, fit: BoxFit.fitWidth,),
    );
  }
  
  buildDescription(String msg){
    return Padding(
        padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_small),
      child: Text(msg, style: MyTextStyle.LIST_BODY,),
    );
  }


  buildBottom(OscQuestion item){
    return Padding(
      padding: EdgeInsets.only(top: paddingChildVertical),
      child: Row(
        children: <Widget>[
          Text("@${item.author}  ${DateUtil.getDateStrByTimeStr(item.pubDate, format: DateFormat.YEAR_MONTH_DAY_HOUR_MINUTE)}", style: MyTextStyle.LIST_BOTTOM,),
          Expanded(
            child: buildBottomItem("ic_comment_30", "${item.commentCount}"),
          ),
        ],
      ),
    );
  }

  buildBottomItem(String imageName, String text){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_icon_height_smallest, fit: BoxFit.fitWidth,),
        Text(" $text", style: MyTextStyle.LIST_BOTTOM,)
      ],
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    List<OscQuestion> tempList;
    await httpRepository.getQuestionList(pageToken: pageToken, userId: authorId).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscQuestion> result = resp.result;
        if(result != null){
          tempList = result.items;
          if(pageToken == null){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          pageToken = result.nextPageToken;
          if(result.requestCount > result.responseCount){
            controller.loadNoData();
          } else {
            controller.loadComplete();
          }
        }
      }
    });

    size = list?.length??0;
    if(mounted) {
      setState(() {
        controller.refreshCompleted();
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  @override
  bool get wantKeepAlive => true;
}
